package com.example.alarmclock;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

import java.util.concurrent.TimeUnit;

public class AlarmAlertActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private Vibrator vibrator;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_alert);

        TextView alarmLabel = findViewById(R.id.alarm_label);
        Button stopButton = findViewById(R.id.stop_button);
        Button snoozeButton = findViewById(R.id.snooze_button);

        Intent intent = getIntent();
        if (intent.hasExtra("alarm_info")) {
            String alarmInfo = intent.getStringExtra("alarm_info");
            AlarmModel alarm = AlarmModel.fromString(alarmInfo);
            alarmLabel.setText("闹钟响起：" + alarm.getLabel());
        }

        mediaPlayer = MediaPlayer.create(this, R.raw.custom_alarm);
        if (mediaPlayer != null) {
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        }

        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        if (vibrator != null) {
            vibrator.vibrate(new long[]{0, 500, 1000}, 0);
        }

        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopAlarm();
            }
        });

        snoozeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSnoozeDialog();
            }
        });
    }

    private void stopAlarm() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (vibrator != null) {
            vibrator.cancel();
        }
        finish();
    }

    private void showSnoozeDialog() {
        DialogFragment dialog = new DelayDialogFragment();
        dialog.show(getSupportFragmentManager(), "SnoozeDialog");
    }

    public void snoozeAlarm(int delayMinutes) {
        Intent intent = getIntent();
        if (intent.hasExtra("alarm_info")) {
            String alarmInfo = intent.getStringExtra("alarm_info");

            long snoozeTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(delayMinutes);

            AlarmHelper.setAlarmWithTriggerTime(this, snoozeTime, alarmInfo);
        }
        stopAlarm();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopAlarm();
    }
}



